package com.lb.trac.pojo.condition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.lb.trac.util.SQLCondition;

public class FindTicketsByUserFilters implements SQLCondition {

	private Map<String,Map<Integer,Object>> params = new HashMap<String,Map<Integer,Object>>();
	public static final int IN_CONDITION = 0;
	public static final int EQ_CONDITION=1;
	
	
	@Override
	public Criterion create(Object... params) {
		Iterator<String> itFilters = this.params.keySet().iterator();
		List<Criterion> criterions = new ArrayList<Criterion>(); 
		while(itFilters.hasNext()){
			String filterName = itFilters.next();
			Map<Integer,Object> m = this.params.get(filterName);
			Iterator<Integer> it = m.keySet().iterator();
			while(it.hasNext()){
				int op = it.next();
				Object value = m.get(op);
				switch(op){
				case IN_CONDITION:
					criterions.add(Restrictions.in(filterName, (Object[]) value));
					break;
				case EQ_CONDITION:
					criterions.add(Restrictions.eq(filterName, value));
					break;
				}
			}
		}
		Criterion global = null;
		for (Iterator iterator = criterions.iterator(); iterator.hasNext();) {
			Criterion criterion = (Criterion) iterator.next();
			global = global!=null?Restrictions.and(global, criterion):criterion;
		}
		return global;
	}
	
	public void add(String filterName,Map<Integer,Object> value){
		params.put(filterName, value);
	}

}
